//
//  AppDelegate.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/4/19.
//

#import "AppDelegate.h"
#import <WXApi.h>
#import "NeoNuiTtsManager.h"


@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [NSThread sleepForTimeInterval:0.5];
    
    
    //微信注册
    [WXApi registerApp:WXAPPID universalLink:UNIVERSALLINK];
    //bugly
    [Bugly startWithAppId:BUGLYID];
    
    //语音播放设置
    [self listentTypeSet];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needLogin) name:@"kJPUserTokenIllegalNotification" object:nil];

    return YES;
}

#pragma mark - 设置静音模式下也能播放音频
-(void)listentTypeSet{
    NSError *setCategoryError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
    
    if (setCategoryError) {
        NSLog(@"Error setting category: %@", [setCategoryError localizedDescription]);
    }
    
    NSError *activationError = nil;
    [[AVAudioSession sharedInstance] setActive:YES error:&activationError];
    
    if (activationError) {
        NSLog(@"Error activating session: %@", [activationError localizedDescription]);
    }
}


#pragma mark - 微信相关需要
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
   return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}


//微信回调
- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        //授权回调
        SendAuthResp *authResp = (SendAuthResp *)resp;
        if (authResp.errCode == WXSuccess) {
            NSString *code = authResp.code;
            //通过code获取access token 和 open ID
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXLoginSuccess" object:code];
        }else{
            //错误信息
            if(authResp.errCode == WXErrCodeUserCancel){
                [JPProgressHUD showMsg:@"用户取消授权"];
            }else if (authResp.errCode == WXErrCodeAuthDeny){
                [JPProgressHUD showMsg:@"授权失败"];
            }else if (authResp.errCode == WXErrCodeCommon){
                [JPProgressHUD showMsg:@"授权错误"];
            }else if (authResp.errCode == WXErrCodeSentFail){
                [JPProgressHUD showMsg:@"发送授权失败"];
            }else if (authResp.errCode == WXErrCodeUnsupport){
                [JPProgressHUD showMsg:@"微信不支持授权"];
            }
        }
    }else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        if (sendResp.errCode == WXSuccess) {
            // 分享成功
            dispatch_async(dispatch_get_main_queue(), ^{
                [JPProgressHUD showMsg:@"分享成功"];
            });
        } else {
            // 分享失败
            dispatch_async(dispatch_get_main_queue(), ^{
                [JPProgressHUD showMsg:@"分享失败"];
            });
        }
    }
}


#pragma mark - 登录过期 退出登录
-(void)needLogin{
    //清除本地数据
//    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"loginMode"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"phone"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"nickname"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"avatar"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"access_token"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"sex"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"introduction"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"goldNumber"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"signCount"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"wordNumber"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"mode"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"downTime"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"downTimeName"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"downTimeCount"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"addGoldNumber"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"unionid"];
    //提示用户
    [JPProgressHUD showMsg:@"登录过期"];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // 移除观察者
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"kJPUserTokenIllegalNotification" object:nil];
    [[NeoNuiTtsManager sharedManager] releaseNui];
}


- (void)applicationWillEnterForeground:(UIApplication *)application{
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
    
}

-(void)applicationWillResignActive:(UIApplication *)application{
    
}

-(void)applicationDidBecomeActive:(UIApplication *)application{
    
}


#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options API_AVAILABLE(ios(13.0)){
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions API_AVAILABLE(ios(13.0)){
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}


@end
